﻿using System.Security.Claims;
using System.Security.Principal;

namespace Mate.Framework.Extensions
{
    /// <summary>
    /// 当前登录用户信息
    /// </summary>
    public static class IdentityExtension
    {
        /// <summary>
        /// 当前登录用户姓名
        /// </summary>
        /// <param name="identity"></param>
        /// <returns></returns>
        public static string UserName(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("UserName");
            return (claim != null) ? claim.Value : string.Empty;
        }

        /// <summary>
        /// 当前登录用户账号
        /// </summary>
        /// <param name="identity"></param>
        /// <returns></returns>
        public static string UserNo(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("UserNo");
            return (claim != null) ? claim.Value : string.Empty;
        }

        /// <summary>
        /// 当前登录用户id
        /// </summary>
        /// <param name="identity"></param>
        /// <returns></returns>
        public static int Id(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("Id");
            if (claim == null)
            {
                return 0;
            }
            int id = 0;
            int.TryParse(claim.Value, out id);
            return id;
        }

        /// <summary>
        /// 当前登录用户角色id
        /// </summary>
        /// <param name="identity"></param>
        /// <returns></returns>
        public static int RoleId(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("RoleId");
            if (claim == null)
            {
                return 0;
            }
            int id = 0;
            int.TryParse(claim.Value, out id);
            return id;
        }


        public static string Find(this IIdentity identity, string type)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst(type);
            return (claim != null) ? claim.Value : string.Empty;
        }

    }
}
